import React, { useState, useEffect } from 'react';
import { Icon, Tooltip, Popconfirm, Modal, message, Spin, Tag, Switch } from 'antd';
import classNames from 'classnames';
import { connect } from 'dva';
import { DndProvider } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import { useFullscreen } from '@umijs/hooks';
import IconFont from '@/components/IconFont';
import request from '@/utils/request';
import { dealId } from './components/utils';
import DesignerContext from './components/DesignerContext';
import Left from './components/Left';
import Right from './components/Right';
import Canvas from './components/Canvas';
import LinkageRule from './components/LinkageRule';
import SlickForm from './components/SlickForm';
import styles from './styles.less';

function FormDesigner({
  formVersionId = 31002,
  formId = 31002,
  size: { height, fullHeight },
  formSchema,
  vertical,
  columnNum,
  labelWidth,
  submitUrl,
  saveUrl,
  needSubmit,
  needSave,
  needBack,
  linkages,
  initloading,
  onBack = () => {},
  dispatch,
}) {
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const { ref, isFullscreen, setFull, exitFull } = useFullscreen();

  useEffect(() => {
    if (formVersionId && formVersionId !== -1) {
      // 获取画布中的模板数据
      dispatch({
        type: 'formDesigner/getInitData',
        payload: { formVersionId },
      });
    } else {
      message.warning('缺少formVersionId');
    }
  }, [formVersionId, dispatch]);

  useEffect(() => {
    setLoading(initloading);
  }, [initloading]);

  return (
    <DndProvider backend={HTML5Backend}>
      <DesignerContext.Provider value={{ formVersionId, formId }}>
        <div ref={ref} className={classNames('media-box', styles.container)}>
          <Spin spinning={loading}>
            <div
              className={classNames('media-right', styles.right)}
              style={{ height: isFullscreen ? fullHeight : height - 2 }}
            >
              <Right />
            </div>
            <div
              className={classNames('media-left', styles.left)}
              style={{ height: isFullscreen ? fullHeight : height - 2 }}
            >
              {/* <div className="padding">
          <Input.Search placeholder="输入关键字" />
        </div> */}
              <Left />
            </div>
            <div
              className={classNames('media-body', styles.main)}
              style={{ height: isFullscreen ? fullHeight : height - 2 }}
            >
              <div className={styles.toolbar}>
                <div className="pull-left">
                  <span className={styles.back} onClick={onBack}>
                    <Icon type="left" />
                  </span>
                  <Tag color="blue" className="margin-left">
                    表单ID: {formVersionId}
                  </Tag>
                  <LinkageRule container={ref} />
                </div>
                <div className="pull-right">
                  <Tooltip
                    placement={isFullscreen ? 'bottom' : 'top'}
                    title="切换隐藏项"
                    getPopupContainer={() => ref.current}
                  >
                    <Switch
                      style={{ marginTop: -3 }}
                      size="small"
                      defaultChecked
                      onChange={checked => {
                        dispatch({
                          type: 'formDesigner/update',
                          payload: { showHideItem: checked },
                        });
                      }}
                    />
                  </Tooltip>
                  <Tooltip
                    placement={isFullscreen ? 'bottom' : 'top'}
                    title="清空画布"
                    getPopupContainer={() => ref.current}
                  >
                    <Popconfirm
                      getPopupContainer={() => ref.current}
                      placement={isFullscreen ? 'bottom' : 'left'}
                      cancelText="点错了"
                      title="亲！确定要清空画布吗？"
                      onConfirm={() => dispatch({ type: 'formDesigner/clear' })}
                    >
                      <IconFont type="icon-trash" className={styles.action} />
                    </Popconfirm>
                  </Tooltip>
                  <Tooltip
                    placement={isFullscreen ? 'bottom' : 'top'}
                    title="全屏"
                    getPopupContainer={() => ref.current}
                  >
                    {isFullscreen ? (
                      <IconFont
                        type="icon-exit-fullscreen"
                        className={styles.action}
                        onClick={exitFull}
                      />
                    ) : (
                      <Icon type="fullscreen" className={styles.action} onClick={setFull} />
                    )}
                  </Tooltip>
                  <Tooltip
                    placement={isFullscreen ? 'bottom' : 'top'}
                    title="预览"
                    getPopupContainer={() => ref.current}
                  >
                    <Icon type="eye" className={styles.action} onClick={() => setVisible(true)} />
                  </Tooltip>
                  <Tooltip
                    placement={isFullscreen ? 'bottom' : 'top'}
                    title="保存模板"
                    getPopupContainer={() => ref.current}
                  >
                    <Icon
                      type="save"
                      className={styles.action}
                      onClick={() => {
                        if (Array.isArray(formSchema) && formSchema.length > 0) {
                          setLoading(true);

                          // 保证全屏的时候 不会被挡住
                          message.config({
                            getContainer: () => ref.current,
                          });

                          request('pmc/pcms/formDesigner/add', {
                            data: {
                              formVersionId,
                              formId,
                              elementList: dealId(formSchema, false), // 剔除每个节点的__id
                              vertical,
                              labelWidth,
                              eleDriveRuleList: linkages,
                              columnNum,
                              submitUrl,
                              saveUrl,
                              needSubmit,
                              needSave,
                              needBack,
                            },
                          })
                            .then(res => {
                              const { success, errMessage } = res;
                              if (success === true) {
                                // 关闭时主动清除，避免其他模块无法正常使用
                                message.success('保存成功', () => message.destroy());
                              } else {
                                message.error(errMessage, () => message.destroy());
                              }
                            })
                            .always(() => {
                              setLoading(false);
                            });
                        } else if (!Array.isArray(formSchema) || formSchema.length === 0) {
                          message.warning('亲！画布是空的呀！');
                        }
                        //  else if (!submitUrl) {
                        //   message.warning('亲！请配置表单属性<提交地址>！');
                        // }
                      }}
                    />
                  </Tooltip>
                </div>
              </div>
              <div
                className={styles.canvas}
                style={{ height: height - 35 - 2 }}
                onClick={e => {
                  // e.preventDefault();
                  e.stopPropagation();
                  dispatch({
                    type: 'formDesigner/setCurrent',
                    payload: formSchema,
                  });
                }}
              >
                {formSchema.length > 0 ? (
                  <Canvas />
                ) : (
                  <div className="middle-item">
                    <b className="middle-item-hack" />
                    <div className="middle-item-body text-center text-gray">从左侧拖入组件</div>
                  </div>
                )}
              </div>
            </div>
          </Spin>
        </div>

        <Modal
          // className="previewModal"
          getContainer={ref.current}
          title="预览"
          destroyOnClose
          visible={visible}
          width={1002}
          centered
          footer={null}
          onCancel={() => setVisible(false)}
        >
          {/* IMPORVE: 用visible控制,是为了解决actions指向的问题 */}
          {visible && (
            <SlickForm
              mode="view"
              linkages={linkages}
              columnNum={columnNum}
              labelWidth={labelWidth}
              formSchema={formSchema}
              vertical={vertical}
              submitUrl={submitUrl}
              saveUrl={saveUrl}
              needSubmit={needSubmit}
              needSave={needSave}
              needBack={needBack}
            />
          )}
        </Modal>
      </DesignerContext.Provider>
    </DndProvider>
  );
}

export default connect(({ setting, formDesigner, loading }) => ({
  size: setting.size,
  formSchema: formDesigner.formSchema,
  vertical: formDesigner.vertical,
  columnNum: formDesigner.columnNum,
  submitUrl: formDesigner.submitUrl,
  saveUrl: formDesigner.saveUrl,
  needSubmit: formDesigner.needSubmit,
  needSave: formDesigner.needSave,
  needBack: formDesigner.needBack,
  labelWidth: formDesigner.labelWidth,
  linkages: formDesigner.linkages,
  initloading: loading.effects['formDesigner/getInitData'],
}))(FormDesigner);
